package com.example.logtestservice.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 日志发送器 - 通过Netty发送日志到日志分析平台
 */
@Component
@Slf4j
public class LogSender {
    
    @Value("${log.platform.host:localhost}")
    private String logPlatformHost;
    
    @Value("${log.platform.port:9999}")
    private int logPlatformPort;
    
    private EventLoopGroup group;
    private Channel channel;
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    @PostConstruct
    public void init() {
        connectToLogPlatform();
    }
    
    /**
     * 连接到日志分析平台
     */
    private void connectToLogPlatform() {
        group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder());
                        }
                    });
            
            ChannelFuture future = bootstrap.connect(logPlatformHost, logPlatformPort).sync();
            channel = future.channel();
            log.info("成功连接到日志分析平台: {}:{}", logPlatformHost, logPlatformPort);
            
        } catch (Exception e) {
            log.error("连接日志分析平台失败", e);
        }
    }
    
    /**
     * 发送日志到日志分析平台
     */
    public void sendLog(String level, String content, String system) {
        if (channel == null || !channel.isActive()) {
            log.warn("与日志分析平台的连接未建立，尝试重连...");
            connectToLogPlatform();
            return;
        }
        
        try {
            JSONObject logJson = new JSONObject();
            logJson.put("timestamp", LocalDateTime.now().format(formatter));
            logJson.put("level", level);
            logJson.put("system", system);
            logJson.put("content", content);
            logJson.put("sourceId", 4L); // 使用4号采集源（网络日志）
            
            String logMessage = logJson.toJSONString() + "\n";
            channel.writeAndFlush(logMessage);
            log.debug("发送日志: {}", logMessage);
            
        } catch (Exception e) {
            log.error("发送日志失败", e);
        }
    }
    
    /**
     * 发送INFO级别日志
     */
    public void info(String content) {
        sendLog("INFO", content, "TEST-SERVICE");
    }
    
    /**
     * 发送WARN级别日志
     */
    public void warn(String content) {
        sendLog("WARN", content, "TEST-SERVICE");
    }
    
    /**
     * 发送ERROR级别日志
     */
    public void error(String content) {
        sendLog("ERROR", content, "TEST-SERVICE");
    }
    
    /**
     * 发送DEBUG级别日志
     */
    public void debug(String content) {
        sendLog("DEBUG", content, "TEST-SERVICE");
    }
    
    @PreDestroy
    public void shutdown() {
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
        log.info("日志发送器已关闭");
    }
}
